package cn.aiweiyi.qingjing.coupon.template.converter;

import cn.aiweiyi.qingjing.coupon.template.entity.CouponTemplate;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author 青衿
 * @Date 2020/11/17 9:34
 * 自定义序列化器
 * 用于将优惠券模板对象,转换为满足本项目需要的JSON格式
 **/
public class CouponTemplateSerializer extends JsonSerializer<CouponTemplate> {

    @Override
    public void serialize(CouponTemplate template, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException {
        //开始序列化对象
        generator.writeStartObject();
        generator.writeStringField("id", template.getId().toString());
        generator.writeStringField("name", template.getName());
        generator.writeStringField("logo", template.getDesc());
        generator.writeStringField("desc", template.getDesc());
        generator.writeStringField("category", template.getCategory().getDesc());
        generator.writeStringField("productLine", template.getProductLine().getDesc());
        generator.writeStringField("count", template.getCount().toString());
        generator.writeStringField("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(template.getCreateTime()));
        generator.writeStringField("userId",
                template.getUserId().toString());
        generator.writeStringField("key",
                template.getKey() + String.format("%04d",
                        template.getId()));
        generator.writeStringField("target",
                template.getTarget().getDesc());
        generator.writeStringField("rule",
                JSON.toJSONString(template.getRule()));
        //结束序列化对象
        generator.writeEndObject();
    }
}
